package com.cskaoyan.market.service;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.cskaoyan.market.aliyun.AliyunProperties;
import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.db.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/5/21 10:20
 * @Version 1.0
 */
@Component
public class AliyunService implements CloudService{

    @Autowired
    AliyunProperties aliyunProperties;
    @Autowired
    MarketStorageMapper marketStorageMapper;


    private ConcurrentHashMap<String, Long> lastSentTimestamps = new ConcurrentHashMap<>();

    @Override
    public MarketStorage oss(InputStream inputStream) throws IOException {
        long size=inputStream.available();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //objectMetadata.setContentType("image/jpg");
        OSS ossClient = new OSSClientBuilder().build(aliyunProperties.getOss().getEndPoint(), aliyunProperties.getAccessKeyId(), aliyunProperties.getAccessKeySecret());
        // 123123312312.png
        String fileName = UUID.randomUUID().toString().replaceAll("-","") + ".png";
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        PutObjectResult putObjectResult = ossClient.putObject(aliyunProperties.getOss().getBucketName(), fileName, inputStream,objectMetadata);

        ossClient.shutdown();
        // https://{bucketName}.{endPoint}/filename
        String url = "https://" + aliyunProperties.getOss().getBucketName() + "." + aliyunProperties.getOss().getEndPoint() + "/" + fileName;
        String key=fileName;
        String name=fileName;
        String type="/image/png";

        LocalDateTime addTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();
        Boolean deleted = false;
        try{
            MarketStorage marketStorage = new MarketStorage();
            marketStorage.setId(null);
            marketStorage.setKey(key);
            marketStorage.setName(name);
            marketStorage.setType(type);
            marketStorage.setSize((int) size);
            marketStorage.setUrl(url);
            marketStorage.setAddTime(addTime);
            marketStorage.setUpdateTime(updateTime);
            marketStorage.setDeleted(deleted);
            marketStorageMapper.insertSelective(marketStorage);
            return marketStorage;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }



    @Override
    public String sms(String phoneNumber) {

        Long lastSentTimestamp = lastSentTimestamps.getOrDefault(phoneNumber, 0L);
        long currentTimeMillis = System.currentTimeMillis();
        if ((currentTimeMillis - lastSentTimestamp) < 60 * 1000) {
            // 如果距离上次发送的时间小于一分钟，则不发送验证码并返回错误信息
            throw new RuntimeException("验证码在一分钟内不能重复发送");
        }
try {
    DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunProperties.getAccessKeyId(), aliyunProperties.getAccessKeySecret());
    IAcsClient client = new DefaultAcsClient(profile);
    CommonRequest request = new CommonRequest();
    request.setMethod(MethodType.POST);
    request.setDomain("dysmsapi.aliyuncs.com");
    request.setVersion("2017-05-25");
    request.setAction("SendSms");
    request.putQueryParameter("RegionId", "cn-hangzhou");
    request.putQueryParameter("PhoneNumbers", phoneNumber);
    request.putQueryParameter("SignName", aliyunProperties.getSms().getSignName());
    request.putQueryParameter("TemplateCode", aliyunProperties.getSms().getTemplateCode());

    Random rand = new Random();
    int randomNum = rand.nextInt(90000) + 10000; // 生成六位数随机数
    String templateParam = "{\"code\":\"" + randomNum + "\"}";
    request.putQueryParameter("TemplateParam", templateParam);

    try {
        CommonResponse response = client.getCommonResponse(request);
        lastSentTimestamps.put(phoneNumber, currentTimeMillis);
        System.out.println(response.getData());
    } catch (ServerException e) {
        e.printStackTrace();
    }  catch (ClientException e) {
        e.printStackTrace();
    } catch (com.aliyuncs.exceptions.ClientException e) {
        throw new RuntimeException(e);
    }

    return randomNum+"";
}catch (Exception e) {
    throw new RuntimeException(e);
}
    }
}
